//
//  RootViewController.m
//  CET
//
//  Created by Kai on 8/27/10.
//  Copyright NONAME STUDIO 2010. All rights reserved.
//

#import "RootViewController.h"
#import "DetailsViewController.h"
#import "CETRecord.h"

@implementation RootViewController

@synthesize recordDownloadsInProgress;
@synthesize admissionCardPrefix;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"CET";
	
	UIBarButtonItem *editButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Edit" 
																	   style:UIBarButtonItemStyleBordered 
																	  target:self 
																	  action:@selector(editButtonPressed:)];
	self.navigationItem.rightBarButtonItem = editButtonItem;
	[editButtonItem release];
	
	UIBarButtonItem *loadMoreButtonitem = [[UIBarButtonItem alloc] initWithTitle:@"Load More" 
																		   style:UIBarButtonItemStyleBordered 
																		  target:self 
																		  action:@selector(loadMoreButtonPressed:)];
	self.navigationItem.leftBarButtonItem = loadMoreButtonitem;
	[loadMoreButtonitem release];
	
	recordDownloadsInProgress = [[NSMutableDictionary alloc] init];
	
	NSString *defaultCard = [[NSUserDefaults standardUserDefaults] objectForKey:@"DefaultCard"];
	if (defaultCard) {
		self.admissionCardPrefix = [defaultCard substringToIndex:10];
		baseRoomNum = [[defaultCard substringWithRange:NSMakeRange(10, 3)] intValue];
	} else {
		self.admissionCardPrefix = @"1201001012";
		baseRoomNum = 72;
	}
	
	sectionNum = 1;
}

- (void)editButtonPressed:(id)sender {
	
	IDInputViewController *idInputViewController = [[IDInputViewController alloc] initWithNibName:@"IDInputViewController" bundle:nil];
	idInputViewController.delegate = self;
	UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:idInputViewController];
	[self presentModalViewController:navController animated:YES];
	idInputViewController.textField.text = [admissionCardPrefix stringByAppendingFormat:@"%.3d01", baseRoomNum];
	[navController release];
	[idInputViewController release];
}

- (void)admissionCardDidSaveWithText:(NSString *)string {
	
	[recordDownloadsInProgress removeAllObjects];
	
	[[NSUserDefaults standardUserDefaults] setObject:string forKey:@"DefaultCard"];
	
	self.admissionCardPrefix = [string substringToIndex:10];
	baseRoomNum = [[string substringWithRange:NSMakeRange(10, 3)] intValue];
	sectionNum = 1;
	
	[self.tableView reloadData];
}

- (void)loadMoreButtonPressed:(id)sender {
	
	sectionNum++;
	
	[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionNum - 1] withRowAnimation:NO];
	[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:sectionNum - 1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)startRecordDownload:(NSString *)admissionCard forIndexPath:(NSIndexPath *)indexPath {
		
    RecordDownloader *recordDownloader = [recordDownloadsInProgress objectForKey:indexPath];
    if (recordDownloader == nil)  {
		
		recordDownloader = [[RecordDownloader alloc] initWithAdmissionCard:admissionCard];
        recordDownloader.indexPathInTableView = indexPath;
        recordDownloader.delegate = self;
        [recordDownloadsInProgress setObject:recordDownloader forKey:indexPath];
        [recordDownloader startDownload];
        [recordDownloader release];
    }
}

- (void)recordDidDownload:(NSIndexPath *)indexPath {
	
	// Not work, may cause crash.
	//[self.tableView beginUpdates];
	//[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:NO];
	//[self.tableView endUpdates];
	
	UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
	
	RecordDownloader *recordDownloader = [recordDownloadsInProgress objectForKey:indexPath];
	
	cell.textLabel.text = [NSString stringWithFormat:@"%.2d %@", indexPath.row + 1, recordDownloader.cetRecord.name];
	cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", recordDownloader.cetRecord.totalScore];
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	if (recordDownloader.cetRecord.totalScore >= 425) {
		cell.textLabel.textColor = [UIColor redColor];
		cell.detailTextLabel.textColor = [UIColor redColor];
	} else {
		cell.textLabel.textColor = [UIColor blackColor];
		cell.detailTextLabel.textColor = [UIColor blackColor];
	}
}


#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return sectionNum;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	
	return [NSString stringWithFormat:@"Room %d -- %@", baseRoomNum + section, self.admissionCardPrefix];
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 30;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
    
	// Configure the cell.
	NSString *card = [NSString stringWithFormat:@"%@%.3d%.2d", admissionCardPrefix, indexPath.section + baseRoomNum, indexPath.row + 1];
	
	[self startRecordDownload:card forIndexPath:indexPath];
	
	RecordDownloader *recordDownloader = [recordDownloadsInProgress objectForKey:indexPath];
	if (recordDownloader && recordDownloader.didFinishLoading) {
		cell.textLabel.text = [NSString stringWithFormat:@"%.2d %@", indexPath.row + 1, recordDownloader.cetRecord.name];
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", recordDownloader.cetRecord.totalScore];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		
		if (recordDownloader.cetRecord.totalScore >= 425) {
			cell.textLabel.textColor = [UIColor redColor];
			cell.detailTextLabel.textColor = [UIColor redColor];
		} else {
			cell.textLabel.textColor = [UIColor blackColor];
			cell.detailTextLabel.textColor = [UIColor blackColor];
		}
	} else {
		cell.textLabel.text = @"Loading...";
		cell.detailTextLabel.text = @"";
		cell.accessoryType = UITableViewCellAccessoryNone;
	}

    return cell;
}


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	RecordDownloader *recordDownloader = [recordDownloadsInProgress objectForKey:indexPath];
	if (recordDownloader.didFinishLoading == NO) {
		return;
	}
	
	DetailsViewController *detailsViewController = [[DetailsViewController alloc] initWithStyle:UITableViewStyleGrouped];
	
	detailsViewController.cetRecord = [recordDownloader cetRecord];
	
	[self.navigationController pushViewController:detailsViewController animated:YES];
	[detailsViewController release];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
		
	[recordDownloadsInProgress release];
	
	[admissionCardPrefix release];
	
    [super dealloc];
}


@end

